package com.myiam.idm.core.services.impl.helper;

import java.util.Iterator;
import java.util.List;

import com.myiam.idm.core.model.Account;
import com.myiam.idm.core.model.Email;
import com.myiam.idm.core.model.Identity;
import com.myiam.idm.core.model.PhoneNumber;
import com.myiam.idm.core.model.Role;
import com.myiam.idm.meta.model.MmAccount;
import com.myiam.idm.meta.model.MmIdentity;
import com.myiam.idm.meta.model.MmRole;

public class ModelToMetaModel {

	
	public static MmAccount accountM2MM(Account account ) {
		MmAccount metaAccount = new MmAccount();
		return metaAccount;
	}
	
	
	public static MmRole roleToM2MM(Role role ) {
		MmRole root = flatMapRole(role);
		
		if (role.hasChildren()) {
			processChildren(root, role);
		}		
		return root;
	}
	
	private static void processChildren(MmRole mRole, Role role) {
		
		Iterator<Role> childrenIt = role.getChildrenAsIterator();
		while (childrenIt.hasNext()) {
			Role child = (Role)childrenIt.next();

			
			MmRole mChildRole = flatMapRole(child);
			mChildRole.setParent(mRole);
			mRole.addChild(mChildRole);
			
			if (child.hasChildren()) {
				processChildren(mRole, role);
			}
			
			
		}
		
	}
	
	
	public static MmRole flatMapRole(Role role) {
		MmRole mRole = new MmRole();
		mRole.setName(role.getType());
		mRole.setType(role.getType());
		mRole.setId(role.getId());
		return mRole;
	}
	
	
	/**
	 * 
	 * @param identity
	 * @return
	 */
	public static MmIdentity identityM2MM(Identity identity ) {
		MmIdentity metaIdentity = new MmIdentity();
		
	
		metaIdentity.setFirstName(identity.getFirstName());
		metaIdentity.setLastName(identity.getLastName());
		
		
		List<PhoneNumber> phoneNumbers =  identity.getPhonenumbers();
		
		if(phoneNumbers != null ) {
			Iterator<PhoneNumber> it = phoneNumbers.iterator();
			while (it.hasNext()) {
				PhoneNumber pn = it.next();
				metaIdentity.addPhoneNumber(pn.getPhoneAsInternationalString());
			}
		}
		
		List<Email> emails = identity.getEmails();
		
		if (emails != null) {
			Iterator <Email>it = emails.iterator();
			while(it.hasNext()) {
				Email email = it.next();
				metaIdentity.addEmail(email.getEmail(), email.getTypeAsString());
			}
		}
		
		return metaIdentity;
	}
		
			
	
	public static Identity MM2identityM(MmIdentity metaIidentity ) {
		Identity identity = new Identity();

		identity.setFirstName(metaIidentity.getFirstName());
		identity.setLastName(metaIidentity.getLastName());
		
		
		return identity;
	}

	
	
}
